package com.feijia.aijingjingus;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.feijia.aijingjingus.util.PreferencesUtils;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.*;

public class ImprovePersonalInformationActivity extends AppCompatActivity {
    ImageButton imageButton6;
    RelativeLayout relativeLayout;
    LinearLayout linearLayout3;
    LoadingDialog ld;
    TextView etNickName,textView21;
    TextView tvUserNum;
    TextView etFirstDay, etLastDay;
    TextView etMenstruation;
    TextView etAveragePeriodLength;
    TextView etAge;
    OptionsPickerView pvNickName, pvAge, pvMenstruation, pvPeriod, pvLogout, pvFeedback, pvAssociatedCode;
    TimePickerView pvFirstDay;

    private ImageView mImageViewImage;
    int Age;
    private RelativeLayout rlMain, rlLoading;
    Handler handler = new Handler();
    Context context = this;
    private SharedPreferences sp;
    private static final int PICTURE_FROM_CAMERA = 101;
    private static final int PICTURE_FROM_GALLERY = 102;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private boolean gettingAssociatedCode = false;

    private File file;

    Runnable UpdateOp;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_improve_personal_information_layout);
//        if(PreferencesUtils.getString(this,PreferencesUtils.PREFERENCE_NAME).equals("男")){
////            用户男性时修改UI背景色
//            imageButton6=(ImageButton)findViewById(R.id.imageButton6);
//            textView21=(TextView)findViewById(R.id.textView21);
//            textView21.setTextColor(getColor(R.color.womain_pink));
//            imageButton6.setImageDrawable(getDrawable(R.drawable.sman));
//            relativeLayout=(RelativeLayout)findViewById(R.id.relativeLayout);
//            relativeLayout.setBackground(getDrawable(R.drawable.top_bar_with_shadow_two));
//        }


        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        etNickName = (TextView) findViewById(R.id.etNickName);
        etFirstDay = (TextView) findViewById(R.id.etFirstDay);
        etLastDay = (TextView) findViewById(R.id.etLastDay);
        etMenstruation = (TextView) findViewById(R.id.etMenstruation);
        etAveragePeriodLength = (TextView) findViewById(R.id.etAveragePeriodLength);
        etAge = (TextView) findViewById(R.id.etAge);
        rlMain = (RelativeLayout) findViewById(R.id.rlUser);
        rlLoading = (RelativeLayout) findViewById(R.id.rlUserLoading);
        tvUserNum = (TextView) findViewById(R.id.tvUserNum);

        NickName = sp.getString("NickName", "");
        Age = sp.getInt("Age", 0);
        FirstDay = sp.getString("FirstDay", "");
        LastDay = sp.getString("LastDay", "");
        Menstruation = sp.getInt("Menstruation", 0);
        PeriodLength = sp.getInt("PeriodLength", 0);
        tvUserNum.setText(GUserNum);

        UpdateOp = new Runnable() {
            @Override
            public void run() {
                NickName = etNickName.getText().toString();
                FirstDay = etFirstDay.getText().toString();
                LastDay = etLastDay.getText().toString();
                if (!etAge.getText().toString().isEmpty()) {
                    Age = Integer.parseInt(etAge.getText().toString());
                }
                if (!etMenstruation.getText().toString().isEmpty()) {
                    Menstruation = Integer.parseInt(etMenstruation.getText().toString());
                }
                if (!etAveragePeriodLength.getText().toString().isEmpty()) {
                    PeriodLength = Integer.parseInt(etAveragePeriodLength.getText().toString());
                }
                JSONObject root = new JSONObject();
                SharedPreferences.Editor editor = sp.edit();
                try {
                    root.put("UserNo", Long.parseLong(GUserNum));
                    if (!NickName.isEmpty()) {
                        root.put("UserNickname", NickName);
                        editor.putString("NickName", NickName);
                    }
                    if (Age != 0) {
                        root.put("Age", Age);
                        editor.putInt("Age", Age);
                    }
                    if (!FirstDay.isEmpty()) {
                        root.put("StartDay", FirstDay);
                        editor.putString("FirstDay", FirstDay);
                    }
                    if (!LastDay.isEmpty()) {
                        root.put("EndDay", LastDay);
                        editor.putString("LastDay", LastDay);
                    }
                    if (Menstruation != 0) {
                        root.put("Menstruation", Menstruation);
                        editor.putInt("Menstruation", Menstruation);
                    }
                    if (PeriodLength != 0) {
                        root.put("PeriodLength", PeriodLength);
                        editor.putInt("PeriodLength", PeriodLength);
                    }
                    editor.apply();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/updateUser.php");
                System.out.println(out.toString());
                /* //操作结果的提示
                String tempStr = null;
                try {
                    tempStr = out.get("OperateResult").toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                final String ResultCode = tempStr;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (ResultCode != null && ResultCode.compareTo("1") >= 0) {

                            //Toast.makeText(getApplicationContext(), context.getString(R.string.modifySuccessfully),
                            //        Toast.LENGTH_SHORT).show();

                        } else {
                            //Toast.makeText(getApplicationContext(), context.getString(R.string.modifyUnsuccessfully),
                            //        Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                */
            }
        };

        final Runnable runnableUi = new Runnable() {
            @Override
            public void run() {
                //更新界面

                if (!NickName.isEmpty()) {
                    etNickName.setText(NickName);
                }
                if (Age != 0) {
                    etAge.setText("" + Age);
                }
                if (!FirstDay.isEmpty()) {
                    etFirstDay.setText(FirstDay);
                }
                if (!LastDay.isEmpty()) {
                    etLastDay.setText(LastDay);
                }
                if (Menstruation != 0) {
                    etMenstruation.setText("" + Menstruation);
                }
                if (PeriodLength != 0) {
                    etAveragePeriodLength.setText("" + PeriodLength);
                }
                if (ld != null)
                    ld.loadSuccess();
                //rlMain.setVisibility(View.VISIBLE);
                //rlLoading.setVisibility(View.INVISIBLE);
            }

        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!NickName.isEmpty() && Age != 0 && !FirstDay.isEmpty() && Menstruation != 0 && PeriodLength != 0) {
                    handler.post(runnableUi);
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ld = new LoadingDialog(context);
                            ld.setLoadingText(" ")
                                    .setSuccessText(" ")
                                    .setFailedText(" ")
                                    .setTextSize(0)
                                    /*.setLoadingText(getString(R.string.Load_Data_str))
                                    .setSuccessText(getString(R.string.Load_Data_Success_str))
                                    .setFailedText(getString(R.string.Load_Data_Failed_str))
                                    */
                                    .closeSuccessAnim()
                                    .show();
                        }
                    });

                    ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                    // 检查网络连接，如果无网络可用，就不需要进行连网操作等
                    NetworkInfo info = manager.getActiveNetworkInfo();
                    if (info == null || !manager.getBackgroundDataSetting()) {
                        Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ld.loadFailed();
                            }
                        });
                        return;
                    }
                    JSONObject root = new JSONObject();
                    try {
                        root.put("UserNo", Long.parseLong(GUserNum));
                        root.put("DetectionDateStart", "2017-04-21");
                        root.put("DetectionDateEnd", "2017-04-21");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/getUserData.php");
                    if (out == null) {
                        Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    System.out.println(out);
                    SharedPreferences.Editor editor = sp.edit();
                    try {
                        if (!out.isNull("UserNickname")) {
                            NickName = out.get("UserNickname").toString();
                            editor.putString("NickName", NickName);
                        }
                        if (!out.isNull("Age")) {
                            Age = out.getInt("Age");
                            editor.putInt("Age", Age);
                        }
                        if (!out.isNull("StartDay")) {
                            FirstDay = out.get("StartDay").toString();
                            editor.putString("FirstDay", FirstDay);
                        }
                        if (!out.isNull("EndDay")) {
                            LastDay = out.get("EndDay").toString();
                            editor.putString("LastDay", LastDay);
                        }
                        if (!out.isNull("Menstruation")) {
                            Menstruation = out.getInt("Menstruation");
                            editor.putInt("Menstruation", Menstruation);
                        }
                        if (!out.isNull("Sex")) {
                            Sex = out.getInt("Sex");
                            editor.putInt("Sex", Sex);
                        }
                        if (!out.isNull("AssociatedUser")) {
                            AssociatedUser = out.getString("AssociatedUser");
                            editor.putString("AssociatedUser", AssociatedUser);
                        }
                        if (!out.isNull("PeriodLength")) {
                            PeriodLength = out.getInt("PeriodLength");
                            editor.putInt("PeriodLength", PeriodLength);
                        }
                        editor.apply();
                        handler.post(runnableUi);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        mImageViewImage = (ImageView) findViewById(R.id.mImageViewImage);
        String path = Environment.getExternalStorageDirectory() + "/w65/icon_bitmap/" + "myicon.png";
        Bitmap bmp = getDiskBitmap(path);
        if (bmp != null && bmp.getHeight() > 0 && bmp.getWidth() > 0) {
            mImageViewImage.setImageBitmap(getDiskBitmap(path));
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                etNickName.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        new Thread(UpdateOp).start();
                    }
                });
            }
        }).start();
    }

    public void onClickDetection(View view) {
        Intent intent = new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            Intent intent = new Intent("controlCenterActivity");
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
        return false;
    }

    public void onClickNickName(View view) {

        pvNickName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
            }
        })

                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        etDialogNickName.setText(NickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                etNickName.setText(etDialogNickName.getText());
                                new Thread(UpdateOp).start();
                                pvNickName.returnData();
                                pvNickName.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvNickName.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .build();
        pvNickName.show();
    }

    public void onClickPickAge(View view) {
        final int StartAge = 14;
        pvAge = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                etAge.setText("" + (StartAge + options1));
                new Thread(UpdateOp).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_age_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvAge.returnData();
                                pvAge.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvAge.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(36)
                .isDialog(true)
                .setBgColor(0xEEEEEE)
                .build();
        pvAge.setPicker(new ArrayList<String>() {
            {
                for (int i = StartAge; i < 81; i++) {
                    add("" + i);
                }
            }
        });
        pvAge.setSelectOptions(10);
        pvAge.show();
    }

    public void onClickMenstruation(View view) {
        final int StartMenstruation = 20;
        pvMenstruation = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                etMenstruation.setText("" + (StartMenstruation + options1));
                new Thread(UpdateOp).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_menstruation_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvMenstruation.returnData();
                                pvMenstruation.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvMenstruation.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setContentTextSize(36)
                .setBgColor(0xEEEEEE)
                .build();
        pvMenstruation.setPicker(new ArrayList<String>() {
            {
                for (int i = StartMenstruation; i < 41; i++) {
                    add("" + i);
                }
            }
        });
        pvMenstruation.setSelectOptions(8);
        pvMenstruation.show();
    }

    public void onClickAveragePeriodLength(View view) {
        final int StartPeriod = 2;
        pvPeriod = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                etAveragePeriodLength.setText("" + (StartPeriod + options1));
                new Thread(UpdateOp).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_period_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvPeriod.returnData();
                                pvPeriod.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvPeriod.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setContentTextSize(36)
                .setBgColor(0xEEEEEE)
                .build();
        pvPeriod.setPicker(new ArrayList<String>() {
            {
                for (int i = StartPeriod; i < 8; i++) {
                    add("" + i);
                }
            }
        });
        pvPeriod.setSelectOptions(2);
        pvPeriod.show();
    }

    public void onClickFirstDay(View view) {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(2013, 0, 1);
        endDate.set(2130, 11, 31);
        pvFirstDay = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                etFirstDay.setText(format.format(date));
                new Thread(UpdateOp).start();
                //tvTime.setText(getTime(date));
            }
        }).setLayoutRes(R.layout.pickerview_custom_firstday_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                //自定义布局中的控件初始化及事件处理
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvFirstDay.returnData();
                        pvFirstDay.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvFirstDay.dismiss();
                    }
                });

            }
        })
                .setLabel("", "", "", "", "", "")
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .isCyclic(true)//是否循环滚动
                .setContentSize(24)
                .setBgColor(0xEEEEEE)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvFirstDay.show();
    }

    public void onClickFaceImg(View view) {
        Intent intent = new Intent();
        //设置启动相册的Action
        intent.setAction(Intent.ACTION_GET_CONTENT);
        //设置类型
        intent.setType("image/*");
        //启动相册，这里使用有返回结果的启动
        startActivityForResult(intent, PICTURE_FROM_GALLERY);
    }

    public void onClickDetectionHistory(View view) {

        Intent intent = new Intent("detectionHistoryActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void onClickLogout(View view) {
        pvLogout = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
                SharedPreferences.Editor editor = sp.edit();
                //editor.putString("USER_NAME", "");
                editor.clear();
                editor.apply();
                Intent intent = new Intent("MainActivity");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_logout_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLogout.returnData();
                                pvLogout.dismiss();
                            }
                        });

                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLogout.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvLogout.setPicker(new ArrayList<>());//添加数据
        pvLogout.show();
    }

    public void onClickFeedback(View view) {
        pvFeedback = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_feedback_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etFeedback = (EditText) v.findViewById(R.id.etDialogRawDetectionData);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (etFeedback.getText().length() != 0) {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            JSONObject root = new JSONObject();
                                            try {
                                                root.put("UserNo", Long.parseLong(GUserNum));
                                                root.put("FeedbackDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                                root.put("Feedback", etFeedback.getText().toString());
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            JSONObject out = GlobalHelper.PostData(root, "http://aaaaahealth.com/ting/submitFeedback.php");
                                            if (out == null) {
                                                handler.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                                return;
                                            } else {
                                                handler.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(context, context.getString(R.string.ThankFeedback_str), Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                            System.out.println(out);
                                        }
                                    }).start();
                                    pvFeedback.returnData();
                                    pvFeedback.dismiss();
                                } else {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(context, context.getString(R.string.FeedbackCantEmpty), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvFeedback.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .build();
        pvFeedback.show();
    }

    public void onClickBack(View view) {
        finish();
    }

    public void onClickGetAssociatedCode(View view) {
        if(gettingAssociatedCode)
        {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                gettingAssociatedCode=true;
                JSONObject root = new JSONObject();
                try {
                    root.put("UserNo", Long.parseLong(GUserNum));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                final JSONObject out = GlobalHelper.PostData(root, "http://aaaaahealth.com/ting/getAssociatedCode.php");
                if (out == null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                } else {
                    String associatedCodeTemp = "null";
                    try {
                        associatedCodeTemp = out.getString("AssociatedCode");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final String associatedCode = associatedCodeTemp;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            pvAssociatedCode = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                                @Override
                                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                                }
                            }).setLayoutRes(R.layout.pickerview_custom_associated_code_options, new CustomListener() {
                                @Override
                                public void customLayout(View v) {
                                    TextView tvAssociatedCode = (TextView) v.findViewById(R.id.tvAssociatedCode);
                                    gettingAssociatedCode=false;
                                    if(out.isNull("AssociatedUser")) {
                                        tvAssociatedCode.setText(associatedCode);
                                    }else {
                                        TextView tvAssociatedCodeTitle  = (TextView)v.findViewById(R.id.tvAssociatedCodeTitle);
                                        try {
                                            tvAssociatedCodeTitle.setText(getString(R.string.AccountBound_str));
                                            tvAssociatedCode.setText(out.getString("AssociatedUser"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                    tvSubmit.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            pvAssociatedCode.returnData();
                                            pvAssociatedCode.dismiss();
                                        }
                                    });
                                }
                            }).isDialog(true).build();
                            pvAssociatedCode.show();

                        }
                    });
                }
                System.out.println(out);
            }
        }).start();
    }

    public void onClickUpdate(View view) {
        new Thread(UpdateOp).start();
    }

    /**
     * 从本地获取图片
     *
     * @param pathString 文件路径
     * @return 图片
     */

    public Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PICTURE_FROM_CAMERA:
                    Bitmap bp = getCameraBitmap();
                    try {
                        saveFile(bp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mImageViewImage.setImageBitmap(bp);
                    break;
                case PICTURE_FROM_GALLERY:
                    Bitmap bit = getPhotoBitmap(data);
                    bit = toRoundBitmap(bit);
                    try {
                        saveFile(bit);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mImageViewImage.setImageBitmap(bit);
                    break;
            }
        }
    }


    /**
     * 调用系统相机拍照
     */
    private void startCamera() {
        Intent intent = new Intent();
        //启动相机的Action
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //文件的保存位置
        file = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".png");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //设置图片拍摄后保存的位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        //启动相机，这里使用有返回结果的启动
        startActivityForResult(intent, PICTURE_FROM_CAMERA);
    }

    public Bitmap getPhotoBitmap(Intent data) {
        Bitmap bitmap = null;
        Bitmap bit = null;
        try {
            Uri uri = data.getData();
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, 300, 300);
            bit = toRoundBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //return bit;
        return bitmap;
    }

    /**
     * 得到相机拍照后的照片的bitmap
     *
     * @return
     */
    public Bitmap getCameraBitmap() {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.fromFile(file)));
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, 300, 300);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //Bitmap pic = getBitmap();//另一种显示图片的方法
        //toRoundBitmap(pic);
        //返回一个圆形的bitmap
        //return toRoundBitmap(bitmap);
        return bitmap;
    }

    /**
     * 将一个bitmap转化为圆形输出
     *
     * @param bitmap
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int r = 0;
        if (width < height) {
            r = width;
        } else {
            r = height;
        }
        Bitmap backgroundBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(backgroundBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0, 0, r, r);
        canvas.drawRoundRect(rectF, r / 2, r / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, null, rectF, paint);
        return backgroundBitmap;
    }

    public File saveFile(Bitmap bm) throws IOException {
        String path = Environment.getExternalStorageDirectory().toString() + "/w65/icon_bitmap/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File myIconFile = new File(path + "myicon.png");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myIconFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myIconFile;
    }

    public void onClickShop(View view) {
        Intent intent = new Intent("ShoppingActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}